<?php
class ModelToolSeoUrl extends Model {
	/*
	 * get list data
	 */
	public function get($id){
		//$sql = "SELECT url_alias_id, keyword FROM " . DB_PREFIX . "url_alias WHERE `url_alias_id` = '" .$id."'";
		//$sql = "SELECT url_alias_id, keyword FROM " . DB_PREFIX . "url_alias ";
		$sql = " select * from url_alias where query like '%category_id%'";
		$data = $this->db->query($sql);
		return $data->rows;
	}

	/*
	 * update url_alias
	 */
	public function update($id, $value){
		$sql = "update url_alias set keyword='" . $value . "' where url_alias_id = '" . $id . "'";
		$this->db->query($sql);
	}

	/*
	 * rewrite url
	 */
	public function rewrite($link) {
		if ($this->config->get('config_seo_url')) {
			$url_data = parse_url(str_replace('&amp;', '&', $link));
			$url = '';
			$data = array();
			parse_str($url_data['query'], $data);
			foreach ($data as $key => $value) {
				if (($key == 'product_id') || ($key == 'manufacturer_id') || ($key == 'information_id')) {
					$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE `query` = '" . $this->db->escape($key . '=' . (int)$value) . "'");
					if ($query->num_rows) {
						$url .= '/' . $query->row['keyword'];
						unset($data[$key]);
					}
				} elseif ($key == 'path') {
					$categories = explode('_', $value);
					foreach ($categories as $category) {
						$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE `query` = 'category_id=" . (int)$category . "'");

						if ($query->num_rows) {
							$url .= '/' . $query->row['keyword'];
						}
					}
					unset($data[$key]);
				}else if($key == "ajax"){
					$url .= '/ajax';
				}
			}

			if ($url) {
				unset($data['route']);
				unset($data['ajax']);
				$query = '';
				if ($data) {
					foreach ($data as $key => $value) {
						$query .= '&' . $key . '=' . $value;
					}
					if ($query) {
						$query = '?' . str_replace('&amp;', '&', trim($query, '&'));
					}
				}
				return $url_data['scheme'] . '://' . $url_data['host'] . (isset($url_data['port']) ? ':' . $url_data['port'] : '') . str_replace('/index.php', '', $url_data['path']) . $url . $query;
			} else {
				return $link;
			}
		} else {
			return $link;
		}
	}
}
?>